package com.hhkj.admin.common.aspectj;

import cn.hutool.core.util.StrUtil;
import com.hhkj.admin.common.annotation.ClearRedis;
import com.ruoyi.common.core.redis.RedisCache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Timer;
import java.util.TimerTask;

@Component
@Aspect
public class ClearRedisAspect {

    @Autowired
    private RedisCache redisCache;

    private static final Logger logger = LoggerFactory.getLogger(UseRedisAspect.class);

    @Around(value = "@annotation(clearRedis)")
    public Object around(ProceedingJoinPoint joinPoint, ClearRedis clearRedis) {
        String title = clearRedis.value();
        Class clazz = clearRedis.clazz();
        Object result = null;

        //前缀格式化
        if (title.endsWith(":") == false) {
            title = title + StrUtil.COLON;
        }
        //生成key
        String key = title + clazz.getSimpleName();
        try {
            //第一次删除
            redisCache.deleteObject(key);
            //执行方法
            result = joinPoint.proceed();
            //延迟删除
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    redisCache.deleteObject(key);
                }
            };
            timer.schedule(task, 1000);
            return result;
        } catch (Exception e) {
            logger.info(e.getMessage());
        } catch (Throwable e) {
            logger.info(e.getMessage());
        } finally {
            return result;
        }
    }
}
